<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据统计 - CRUD Generator</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css" rel="stylesheet">
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <!-- Common CSS -->
    <link href="/css/common.css" rel="stylesheet">
    
    <style>
        body {
            font-family: 'Inter', sans-serif;
            background: #f8f9fa;
            padding-top: 80px;
        }
        
        .navbar {
            background: white !important;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            position: fixed;
            top: 0;
            width: 100%;
            z-index: 1000;
        }
        
        .main-content {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .page-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 20px;
            padding: 40px;
            margin-bottom: 30px;
            text-align: center;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }
        
        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 30px rgba(0,0,0,0.15);
        }
        
        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        
        .stat-icon {
            width: 60px;
            height: 60px;
            border-radius: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
            color: white;
            margin-bottom: 15px;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 5px;
            color: #2d3748;
        }
        
        .stat-label {
            color: #6c757d;
            font-size: 0.9rem;
            margin-bottom: 10px;
        }
        
        .stat-change {
            font-size: 0.8rem;
            font-weight: 500;
        }
        
        .change-positive {
            color: #28a745;
        }
        
        .change-negative {
            color: #dc3545;
        }
        
        .chart-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            overflow: hidden;
            margin-bottom: 30px;
        }
        
        .chart-header {
            background: #f8f9fa;
            border-bottom: 1px solid #e9ecef;
            padding: 20px 25px;
            font-weight: 600;
            display: flex;
            justify-content: between;
            align-items: center;
        }
        
        .chart-body {
            padding: 25px;
        }
        
        .filter-controls {
            background: white;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
        }
        
        .table-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            overflow: hidden;
        }
        
        .table-header {
            background: #f8f9fa;
            border-bottom: 1px solid #e9ecef;
            padding: 20px 25px;
            font-weight: 600;
        }
        
        .progress-custom {
            height: 8px;
            border-radius: 10px;
            background: #e9ecef;
        }
        
        .progress-bar-custom {
            border-radius: 10px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        
        .metric-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px 0;
            border-bottom: 1px solid #e9ecef;
        }
        
        .metric-item:last-child {
            border-bottom: none;
        }
        
        .metric-label {
            font-weight: 500;
            color: #2d3748;
        }
        
        .metric-value {
            font-weight: 600;
            color: #667eea;
        }
        
        .time-filter {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }
        
        .time-btn {
            padding: 8px 16px;
            border: 1px solid #e9ecef;
            background: white;
            border-radius: 8px;
            color: #6c757d;
            text-decoration: none;
            transition: all 0.3s ease;
        }
        
        .time-btn.active {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-color: transparent;
        }
        
        .time-btn:hover {
            color: #667eea;
            border-color: #667eea;
        }
        
        .export-btn {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            border: none;
            color: white;
            padding: 10px 20px;
            border-radius: 8px;
            font-weight: 500;
        }
        
        .export-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 15px rgba(0,0,0,0.2);
            color: white;
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <div th:replace="fragments/navigation :: navbar"></div>

    <div class="main-content">
        <!-- Page Header -->
        <div class="page-header">
            <h1 class="display-5 mb-3">
                <i class="bi bi-graph-up me-3"></i>
                数据统计分析
            </h1>
            <p class="lead mb-0">系统使用情况、性能指标和业务数据的综合分析</p>
        </div>

        <!-- Filter Controls -->
        <div class="filter-controls">
            <div class="row align-items-center">
                <div class="col-md-6">
                    <div class="time-filter">
                        <a href="#" class="time-btn active" data-period="7d">最近7天</a>
                        <a href="#" class="time-btn" data-period="30d">最近30天</a>
                        <a href="#" class="time-btn" data-period="90d">最近90天</a>
                        <a href="#" class="time-btn" data-period="1y">最近一年</a>
                    </div>
                </div>
                <div class="col-md-6 text-end">
                    <div class="d-flex gap-2 justify-content-end">
                        <select class="form-select" style="width: auto;" id="dataSource">
                            <option value="all">所有数据源</option>
                            <option value="generator">代码生成器</option>

                            <option value="contracts">智能合约</option>
                        </select>
                        <button class="btn btn-outline-primary" onclick="applyFilters()">
                            <i class="bi bi-funnel me-1"></i>应用筛选
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Key Metrics -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                    <i class="bi bi-people"></i>
                </div>
                <div class="stat-value" id="totalUsers">1,234</div>
                <div class="stat-label">总用户数</div>
                <div class="stat-change change-positive">
                    <i class="bi bi-arrow-up me-1"></i>+12.5%
                </div>
            </div>
            
            <div class="stat-card">
                <div class="stat-icon" style="background: linear-gradient(135deg, #28a745 0%, #20c997 100%);">
                    <i class="bi bi-code-slash"></i>
                </div>
                <div class="stat-value" id="generatedProjects">856</div>
                <div class="stat-label">生成项目数</div>
                <div class="stat-change change-positive">
                    <i class="bi bi-arrow-up me-1"></i>+8.3%
                </div>
            </div>
            
            <div class="stat-card">
                <div class="stat-icon" style="background: linear-gradient(135deg, #ffc107 0%, #fd7e14 100%);">
                    <i class="bi bi-file-earmark-code"></i>
                </div>
                <div class="stat-value" id="deployedContracts">342</div>
                <div class="stat-label">部署合约数</div>
                <div class="stat-change change-positive">
                    <i class="bi bi-arrow-up me-1"></i>+15.7%
                </div>
            </div>
            
            <div class="stat-card">
                <div class="stat-icon" style="background: linear-gradient(135deg, #e83e8c 0%, #dc3545 100%);">
                    <i class="bi bi-lightning"></i>
                </div>
                <div class="stat-value" id="apiCalls">45.2K</div>
                <div class="stat-label">API调用次数</div>
                <div class="stat-change change-negative">
                    <i class="bi bi-arrow-down me-1"></i>-2.1%
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Usage Trends Chart -->
            <div class="col-lg-8">
                <div class="chart-card">
                    <div class="chart-header">
                        <h5 class="mb-0">
                            <i class="bi bi-graph-up me-2"></i>使用趋势分析
                        </h5>
                        <div class="dropdown">
                            <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                                选择指标
                            </button>
                            <ul class="dropdown-menu">
                                <li><a class="dropdown-item" href="#" onclick="updateChart('users')">用户增长</a></li>
                                <li><a class="dropdown-item" href="#" onclick="updateChart('projects')">项目生成</a></li>
                                <li><a class="dropdown-item" href="#" onclick="updateChart('contracts')">合约部署</a></li>
                                <li><a class="dropdown-item" href="#" onclick="updateChart('api')">API调用</a></li>
                            </ul>
                        </div>
                    </div>
                    <div class="chart-body">
                        <canvas id="trendsChart" width="400" height="200"></canvas>
                    </div>
                </div>
            </div>
            
            <!-- Performance Metrics -->
            <div class="col-lg-4">
                <div class="chart-card">
                    <div class="chart-header">
                        <h5 class="mb-0">
                            <i class="bi bi-speedometer2 me-2"></i>性能指标
                        </h5>
                    </div>
                    <div class="chart-body">
                        <div class="metric-item">
                            <div class="metric-label">平均响应时间</div>
                            <div class="metric-value">245ms</div>
                        </div>
                        <div class="metric-item">
                            <div class="metric-label">系统可用性</div>
                            <div class="metric-value">99.8%</div>
                        </div>
                        <div class="metric-item">
                            <div class="metric-label">错误率</div>
                            <div class="metric-value">0.12%</div>
                        </div>
                        <div class="metric-item">
                            <div class="metric-label">并发用户数</div>
                            <div class="metric-value">156</div>
                        </div>
                        <div class="metric-item">
                            <div class="metric-label">数据库连接</div>
                            <div class="metric-value">23/100</div>
                        </div>
                        <div class="metric-item">
                            <div class="metric-label">内存使用率</div>
                            <div>
                                <div class="progress-custom">
                                    <div class="progress-bar-custom" style="width: 68%"></div>
                                </div>
                                <small class="text-muted">68%</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Feature Usage -->
            <div class="col-lg-6">
                <div class="chart-card">
                    <div class="chart-header">
                        <h5 class="mb-0">
                            <i class="bi bi-pie-chart me-2"></i>功能使用分布
                        </h5>
                    </div>
                    <div class="chart-body">
                        <canvas id="featureChart" width="400" height="300"></canvas>
                    </div>
                </div>
            </div>
            
            <!-- Geographic Distribution -->
            <div class="col-lg-6">
                <div class="chart-card">
                    <div class="chart-header">
                        <h5 class="mb-0">
                            <i class="bi bi-geo-alt me-2"></i>地理分布
                        </h5>
                    </div>
                    <div class="chart-body">
                        <canvas id="geoChart" width="400" height="300"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <!-- Top Projects Table -->
        <div class="table-card">
            <div class="table-header">
                <h5 class="mb-0">
                    <i class="bi bi-trophy me-2"></i>热门项目排行
                </h5>
            </div>
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>排名</th>
                            <th>项目名称</th>
                            <th>创建者</th>
                            <th>生成次数</th>
                            <th>最后更新</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="projectsTable">
                        <!-- Table content will be loaded here -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <!-- Common JS -->
    <script src="/js/common.js"></script>

    <script>
        let trendsChart, featureChart, geoChart;
        
        // Sample data
        const analyticsData = {
            trends: {
                labels: ['1月', '2月', '3月', '4月', '5月', '6月', '7月'],
                users: [120, 190, 300, 500, 200, 300, 450],
                projects: [80, 150, 220, 380, 150, 250, 320],
                contracts: [30, 60, 90, 150, 80, 120, 180],
                api: [1200, 1900, 3000, 5000, 2000, 3000, 4500]
            },
            features: {
                labels: ['代码生成', '智能合约', '数据统计', '系统设置'],
                data: [35, 25, 20, 12, 8]
            },
            geography: {
                labels: ['北京', '上海', '深圳', '杭州', '广州', '成都'],
                data: [28, 22, 18, 12, 10, 10]
            },
            projects: [
                { rank: 1, name: 'E-Commerce Platform', creator: 'Alice Wang', count: 156, updated: '2024-01-15', status: 'active' },
                { rank: 2, name: 'Supply Chain System', creator: 'Bob Chen', count: 142, updated: '2024-01-14', status: 'active' },
                { rank: 3, name: 'Financial Management', creator: 'Carol Li', count: 128, updated: '2024-01-13', status: 'active' },
                { rank: 4, name: 'IoT Data Platform', creator: 'David Zhang', count: 115, updated: '2024-01-12', status: 'inactive' },
                { rank: 5, name: 'Healthcare System', creator: 'Eva Liu', count: 98, updated: '2024-01-11', status: 'active' }
            ]
        };

        // Initialize page
        document.addEventListener('DOMContentLoaded', function() {
            initCharts();
            loadProjectsTable();
            setupTimeFilters();
            updateMetrics();
        });

        function initCharts() {
            // Trends Chart
            const trendsCtx = document.getElementById('trendsChart').getContext('2d');
            trendsChart = new Chart(trendsCtx, {
                type: 'line',
                data: {
                    labels: analyticsData.trends.labels,
                    datasets: [{
                        label: '用户增长',
                        data: analyticsData.trends.users,
                        borderColor: '#667eea',
                        backgroundColor: 'rgba(102, 126, 234, 0.1)',
                        tension: 0.4,
                        fill: true
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: {
                            display: false
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });

            // Feature Usage Chart
            const featureCtx = document.getElementById('featureChart').getContext('2d');
            featureChart = new Chart(featureCtx, {
                type: 'doughnut',
                data: {
                    labels: analyticsData.features.labels,
                    datasets: [{
                        data: analyticsData.features.data,
                        backgroundColor: [
                            '#667eea',
                            '#28a745',
                            '#ffc107',
                            '#e83e8c',
                            '#6c757d'
                        ]
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: {
                            position: 'bottom'
                        }
                    }
                }
            });

            // Geographic Chart
            const geoCtx = document.getElementById('geoChart').getContext('2d');
            geoChart = new Chart(geoCtx, {
                type: 'bar',
                data: {
                    labels: analyticsData.geography.labels,
                    datasets: [{
                        label: '用户分布',
                        data: analyticsData.geography.data,
                        backgroundColor: 'rgba(102, 126, 234, 0.8)',
                        borderColor: '#667eea',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: {
                            display: false
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        }

        function loadProjectsTable() {
            const tbody = document.getElementById('projectsTable');
            tbody.innerHTML = analyticsData.projects.map(project => `
                <tr>
                    <td>
                        <span class="badge bg-primary">#${project.rank}</span>
                    </td>
                    <td>
                        <strong>${project.name}</strong>
                    </td>
                    <td>${project.creator}</td>
                    <td>
                        <span class="badge bg-success">${project.count}</span>
                    </td>
                    <td>${project.updated}</td>
                    <td>
                        <span class="badge ${project.status === 'active' ? 'bg-success' : 'bg-secondary'}">
                            ${project.status === 'active' ? '活跃' : '非活跃'}
                        </span>
                    </td>
                    <td>
                        <button class="btn btn-sm btn-outline-primary" onclick="viewProject(${project.rank})">
                            <i class="bi bi-eye"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-success" onclick="cloneProject(${project.rank})">
                            <i class="bi bi-files"></i>
                        </button>
                    </td>
                </tr>
            `).join('');
        }

        function setupTimeFilters() {
            document.querySelectorAll('.time-btn').forEach(btn => {
                btn.addEventListener('click', function(e) {
                    e.preventDefault();
                    
                    // Update active state
                    document.querySelectorAll('.time-btn').forEach(b => b.classList.remove('active'));
                    this.classList.add('active');
                    
                    // Update data based on period
                    const period = this.dataset.period;
                    updateDataForPeriod(period);
                });
            });
        }

        function updateChart(metric) {
            const data = analyticsData.trends[metric];
            const labels = {
                users: '用户增长',
                projects: '项目生成',
                contracts: '合约部署',
                api: 'API调用'
            };
            
            trendsChart.data.datasets[0].data = data;
            trendsChart.data.datasets[0].label = labels[metric];
            trendsChart.update();
        }

        function updateDataForPeriod(period) {
            Utils.showLoading();
            
            setTimeout(() => {
                Utils.hideLoading();
                
                // Simulate data update based on period
                const multiplier = period === '7d' ? 0.3 : period === '30d' ? 1 : period === '90d' ? 2.5 : 5;
                
                // Update metrics
                document.getElementById('totalUsers').textContent = Math.floor(1234 * multiplier);
                document.getElementById('generatedProjects').textContent = Math.floor(856 * multiplier);
                document.getElementById('deployedContracts').textContent = Math.floor(342 * multiplier);
                document.getElementById('apiCalls').textContent = (45.2 * multiplier).toFixed(1) + 'K';
                
                // Update charts
                trendsChart.update();
                featureChart.update();
                geoChart.update();
                
                Utils.showToast(`已更新${period}数据`, 'success');
            }, 1000);
        }

        function updateMetrics() {
            // Animate counter numbers
            const counters = document.querySelectorAll('.stat-value');
            counters.forEach(counter => {
                const target = parseInt(counter.textContent.replace(/[^\d]/g, ''));
                let current = 0;
                const increment = target / 50;
                
                const timer = setInterval(() => {
                    current += increment;
                    if (current >= target) {
                        current = target;
                        clearInterval(timer);
                    }
                    
                    if (counter.textContent.includes('K')) {
                        counter.textContent = (current / 1000).toFixed(1) + 'K';
                    } else {
                        counter.textContent = Math.floor(current).toLocaleString();
                    }
                }, 20);
            });
        }

        function applyFilters() {
            const dataSource = document.getElementById('dataSource').value;
            Utils.showLoading();
            
            setTimeout(() => {
                Utils.hideLoading();
                Utils.showToast(`已应用${dataSource}筛选`, 'success');
                
                // Update charts and data based on filter
                trendsChart.update();
                featureChart.update();
                geoChart.update();
                loadProjectsTable();
            }, 1000);
        }

        function refreshData() {
            Utils.showLoading();
            
            setTimeout(() => {
                Utils.hideLoading();
                
                // Refresh all data
                updateMetrics();
                trendsChart.update();
                featureChart.update();
                geoChart.update();
                loadProjectsTable();
                
                Utils.showToast('数据已刷新', 'success');
            }, 1500);
        }

        function exportReport() {
            Utils.showLoading();
            
            setTimeout(() => {
                Utils.hideLoading();
                
                // Simulate report generation
                const reportData = {
                    timestamp: new Date().toISOString(),
                    metrics: {
                        totalUsers: document.getElementById('totalUsers').textContent,
                        generatedProjects: document.getElementById('generatedProjects').textContent,
                        deployedContracts: document.getElementById('deployedContracts').textContent,
                        apiCalls: document.getElementById('apiCalls').textContent
                    },
                    period: document.querySelector('.time-btn.active').textContent
                };
                
                // Create and download file
                const blob = new Blob([JSON.stringify(reportData, null, 2)], { type: 'application/json' });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `analytics-report-${new Date().toISOString().split('T')[0]}.json`;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
                
                Utils.showToast('报告已导出', 'success');
            }, 2000);
        }

        function viewProject(rank) {
            const project = analyticsData.projects.find(p => p.rank === rank);
            Utils.showToast(`查看项目: ${project.name}`, 'info');
        }

        function cloneProject(rank) {
            const project = analyticsData.projects.find(p => p.rank === rank);
            Utils.showToast(`克隆项目: ${project.name}`, 'info');
        }
    </script>
</body>
</html>